package com.example.lj.uav.view;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Point;
import android.location.Location;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextPaint;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.example.lj.uav.MyApplication;
import com.example.lj.uav.R;
import com.example.lj.uav.adapter.ActionAdapter;
import com.example.lj.uav.bean.PointAction;
import com.example.lj.uav.bean.RouteLine;
import com.example.lj.uav.bean.RoutePoint;
import com.example.lj.uav.dao.MyDBDao;
import com.example.lj.uav.enums.PayloadErr;
import com.example.lj.uav.utils.AlarmUtils;
import com.example.lj.uav.utils.DoubleUtils;
import com.example.lj.uav.utils.ImageFileUtils;
import com.example.lj.uav.utils.OnUIUtils;
import com.example.lj.uav.utils.PayloadUtils;
import com.example.lj.uav.utils.ScreenShootUtils;
import com.example.lj.uav.utils.TypeUtils;
import com.example.lj.uav.view.adapter.ViewPagerAdapter;
import com.example.lj.uav.view.base.BaseActivity;
import com.example.lj.uav.view.fragment.FragmentFlyPrepare;
import com.example.lj.uav.view.fragment.FragmentLineSetting;
import com.example.lj.uav.view.fragment.FragmentPointSetting;
import com.example.lj.uav.widget.CommomDialog;
import com.example.lj.uav.widget.SlideRecyclerView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import dji.common.error.DJIError;
import dji.common.flightcontroller.FlightControllerState;
import dji.common.mission.waypoint.Waypoint;
import dji.common.mission.waypoint.WaypointMission;
import dji.common.mission.waypoint.WaypointMissionDownloadEvent;
import dji.common.mission.waypoint.WaypointMissionExecutionEvent;
import dji.common.mission.waypoint.WaypointMissionFinishedAction;
import dji.common.mission.waypoint.WaypointMissionFlightPathMode;
import dji.common.mission.waypoint.WaypointMissionHeadingMode;
import dji.common.mission.waypoint.WaypointMissionUploadEvent;
import dji.common.util.CommonCallbacks;
import dji.sdk.base.BaseProduct;
import dji.sdk.flightcontroller.Compass;
import dji.sdk.flightcontroller.FlightController;
import dji.sdk.mission.waypoint.WaypointMissionOperator;
import dji.sdk.mission.waypoint.WaypointMissionOperatorListener;
import dji.sdk.payload.Payload;
import dji.sdk.products.Aircraft;
import dji.sdk.sdkmanager.DJISDKManager;

import static com.example.lj.uav.MyApplication.mPref;

public class RouteSettingActivity extends BaseActivity implements View.OnClickListener, Handler.Callback, AMap.OnMapScreenShotListener {
    private MapView mapView;
    private AMap aMap;
    private UiSettings uiSettings;
    private List<Marker> markerList = new ArrayList<>();
    private List<RoutePoint> points = new ArrayList<>();
    private int markerIndex;
    private RelativeLayout mRlSave;
    private RelativeLayout mRlEdit;
    private ImageButton mBtnStart;
    private ImageButton mBtnPause;
    private EditText mEtFileName;
    private MyDBDao dao;
    public RouteLine line;
    private boolean isCreating = true;
    private List<String> fileNames;
    private String name;
    private static final int CREATE = 0;
    private static final int UPDATE = 1;
    private int start_flag;
    private boolean isRouteMenuVisible;

    private FrameLayout mLlInfo;
    private RelativeLayout mRlInfoBtn;
    private LinearLayout mLlButtonBar;
    private LinearLayout mLlButtonBar2;
    private RelativeLayout mRlLocation;
    private RelativeLayout mRlExchange;
    private RelativeLayout mRlClear;
    private RelativeLayout mRlDeleteLast;
    private RelativeLayout mRlCurrentLocation;
    private RelativeLayout mRlCompass;
    private RelativeLayout mRlMapType;
    private RelativeLayout mRlEraser;
    private PopupWindow mPopupWindow;
    private ImageView mIvCompass;
    private ImageView mIvInfoToggle;
    private Marker mLocationMarker;
    private ViewPager mVpMenu;
    private List<Fragment> viewList = new ArrayList<>();
    private ViewPagerAdapter viewPagerAdapter;
    private FragmentLineSetting fragmentRouteSetting;
    private FragmentPointSetting fragmentPointSetting;
    private RadioGroup mRg;
    private RadioButton mRbRoute;
    private RadioButton mRbPoint;
    private ImageButton mIbFileName;
    private LinearLayout mLlActionMenu;
    private int selectMarkerPosition;
    private String myLocationStr;
    private String oldImageFilePath;
    private TextView mTvJourney;
    private TextView mTvTime;
    private TextView mTvWaypointQty;
//    private TextView mTvPhotoQty;
    private ImageView mIvAdd;
    private SlideRecyclerView mSRev;
    private ActionAdapter actionAdapter;
    private List<PointAction> actions;
    private Handler handler;
    private PopupWindow actionPopWindow;
    private FragmentManager fragmentManager;
    private FragmentFlyPrepare fragmentFlyPrepare;
    private FragmentTransaction fragmentTransaction;
    private RelativeLayout mRlRouteSetting;
    private RelativeLayout mRlCotainer;
    private BaseProduct product;

    private List<Polyline> polylineList;
    private boolean setComplete = false;
    private boolean hasEdit;
//    private boolean airCraftConnected = false;
    private String savedFileName = "";

    public double droneLocationLat, droneLocationLng;
    public double backLat,backLng;
    private Marker droneMarker = null;
    private FlightController mFlightController;
    public String mFlightMode;
    private Compass compass;

    private List<Waypoint> waypointList = new ArrayList<>();

    public static WaypointMission.Builder waypointMissionBuilder;
    private WaypointMissionOperator instance;
    private WaypointMissionFinishedAction mFinishedAction = WaypointMissionFinishedAction.GO_HOME;
    private WaypointMissionHeadingMode mHeadingMode = WaypointMissionHeadingMode.AUTO;
    private int totalTimeSecond;//飞行时长
    private boolean screenShooted = false;
    private long errTime;
    private int myCh4;
    private PayloadUtils.CallBack payloadCb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route_setting);

        IntentFilter filter = new IntentFilter();
        filter.addAction(MyApplication.FLAG_CONNECTION_CHANGE);
//        registerReceiver(mReceiver, filter);

        initMap(savedInstanceState);
        initView();
        initData();
        initListener();
        addListener();
        initFlightController();
//        updateSecondaryVideoVisibility();
    }

//    private void updateSecondaryVideoVisibility() {
//        if (secondaryFPVWidget.getVideoSource() == null) {
//            secondaryVideoView.setVisibility(View.GONE);
//        } else {
//            secondaryVideoView.setVisibility(View.VISIBLE);
//        }
//    }

//    private void getTimeInterval() {
//        Camera camera = MyApplication.getCameraInstance();
//        if (camera != null) {
//            camera.getPhotoTimeIntervalSettings(new CommonCallbacks.CompletionCallbackWith<SettingsDefinitions.PhotoTimeIntervalSettings>() {
//                @Override
//                public void onSuccess(SettingsDefinitions.PhotoTimeIntervalSettings photoTimeIntervalSettings) {
//                    int time = photoTimeIntervalSettings.getTimeIntervalInSeconds();
//                    if (time > 0) {
//                        mTvPhotoQty.setText(totalTimeSecond / time + "");
//                    }
//                }
//
//                @Override
//                public void onFailure(DJIError djiError) {
//
//                }
//            });
//        }
//    }

//    protected BroadcastReceiver mReceiver = new BroadcastReceiver() {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            OnUIUtils.setToast("BroadcastReceiver");
//            onProductConnectionChange();
//        }
//    };

//    private void onProductConnectionChange() {
//        initFlightController();
//        mBtnStart.setEnabled(true);
//        airCraftConnected = true;
//        OnUIUtils.setToast("onProductConnectionChange");
//    }

    private void initFlightController() {
        showToast("initFlightController");
        product = MyApplication.getProductInstance();
        mFlightController = MyApplication.getFlightControllerInstance();
        if (mFlightController != null) {
            mFlightController.setStateCallback(new FlightControllerState.Callback() {
                @Override
                public void onUpdate(@NonNull FlightControllerState djiFlightControllerCurrentState) {
//                    int level = djiFlightControllerCurrentState.getSatelliteCount();
//                    Log.e("Level", "level = " + level);
//                    if (level == GPSSignalLevel.LEVEL_0.value()) {
//                        showToast("GPS几乎没有信号");
//                    } else if (level == GPSSignalLevel.LEVEL_1.value()) {
//                        showToast("GPS信号非常弱");
//                    } else if (level == GPSSignalLevel.LEVEL_2.value()) {
//                        showToast("GPS信号很弱。在这个级别，飞机的回家功能仍然有效。");
//                    } else if (level == GPSSignalLevel.LEVEL_3.value()) {
//                        showToast("GPS信号很好。在这个级别，飞机可以悬停在空中。");
//                    } else if (level == GPSSignalLevel.LEVEL_4.value()) {
//                        showToast("GPS信号非常好。在这个级别，飞机可以记录起始点。");
//                    } else if (GPSSignalLevel.LEVEL_5.value()<level&&level<GPSSignalLevel.NONE.value()) {
//                        showToast("GPS信号非常强大。");
//                    } else if (level == GPSSignalLevel.NONE.value()) {
//                        showToast("没有GPS信号。1");
//                    } else {
//                        showToast("没有GPS信号。2"+level);
//                    }
                    droneLocationLat = djiFlightControllerCurrentState.getAircraftLocation().getLatitude();
                    droneLocationLng = djiFlightControllerCurrentState.getAircraftLocation().getLongitude();
                    Log.e("locationInfo ： ","droneLocationLat = "+droneLocationLat+",droneLocationLng="+droneLocationLng);
                    mFlightMode = djiFlightControllerCurrentState.getFlightModeString();
                    updateDroneLocation();
                }
            });
            compass = mFlightController.getCompass();
        }

    }

    public RoutePoint getPoint(int position) {
        return points.get(position);
    }

    private void updateDroneLocation() {

//        showToast("lat = " + droneLocationLat + ",lon = " + droneLocationLng);
        LatLng pos = new LatLng(droneLocationLat, droneLocationLng);
        //Create MarkerOptions object
        final MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(pos);
        float aMapAngle = 0;
        if (compass!=null){
            float angle = compass.getHeading();
            if (angle<0){
                aMapAngle = 360+angle;
            }else{
                aMapAngle = angle;
            }
        }
        markerOptions.rotateAngle(aMapAngle);
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_compass_aircraft));
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (droneMarker != null) {
                    droneMarker.remove();
                }
                if (checkGpsCoordination(droneLocationLat, droneLocationLng)) {
                    droneMarker = aMap.addMarker(markerOptions);
                }
            }
        });
    }

    public static boolean checkGpsCoordination(double latitude, double longitude) {
        return (latitude > -90 && latitude < 90 && longitude > -180 && longitude < 180) && (latitude != 0f && longitude != 0f);
    }

    private void cameraUpdate() {
        LatLng pos = new LatLng(droneLocationLat, droneLocationLng);
        float zoomlevel = (float) 18.0;
        CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(pos, zoomlevel);
        aMap.moveCamera(cu);
    }

    private void initMap(Bundle savedInstanceState) {
        mapView = findViewById(R.id.map1);
        mapView.onCreate(savedInstanceState);
        aMap = mapView.getMap();
        final MyLocationStyle myLocationStyle = new MyLocationStyle();
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW);//跟随，1秒刷新
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//显示
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER) ;//连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        myLocationStyle.showMyLocation(true);//显示标记
        aMap.setMyLocationStyle(myLocationStyle);//设置定位模式
        uiSettings = aMap.getUiSettings();//获取uisetting
        uiSettings.setScaleControlsEnabled(true);//显示比例尺
        CameraUpdate mCameraUpdate = CameraUpdateFactory.zoomTo(17);//放缩等级17
        aMap.animateCamera(mCameraUpdate);
        aMap.setOnMarkerDragListener(new AMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
                marker.getPosition();
                for (int i = 0; i < markerList.size(); i++) {
                    if (markerList.get(i).getId().equals(marker.getId())) {
                        markerIndex = i;
                        break;
                    }
                }
            }

            @Override
            public void onMarkerDrag(Marker marker) {
                upDatePointAndLine(markerIndex);
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                Log.e("拖动结束", marker.getPosition().toString());
                points.get(markerIndex).setLongitude(DoubleUtils.doubleFormat(marker.getPosition().longitude, 7));
                points.get(markerIndex).setLatitude(DoubleUtils.doubleFormat(marker.getPosition().latitude, 7));
                fragmentPointSetting.updatePointPosition(markerIndex);
                if (markerList.size() > 0) {
                    float angle = getMarkeraAngle(markerList.get(markerIndex - 1).getPosition(), markerList.get(markerIndex).getPosition());
                    markerList.get(markerIndex - 1).setRotateAngle(angle);
                    markerList.get(markerIndex).setRotateAngle(angle);
                }
                calculateJourneyAndTime();
            }
        });
        aMap.setMyLocationEnabled(true);//允许定位
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {

                String s = location.toString();
                String d[] = s.split("#");
                String province = d[2].substring(d[2].indexOf("=") + 1, d[2].length());
                String city = d[3].substring(d[3].indexOf("=") + 1, d[3].length());
                String district = d[4].substring(d[4].indexOf("=") + 1, d[4].length());
                myLocationStr = province + " " + city + " " + district;
            }
        });
    }

    private void setMapClickListEnable(boolean enable) {
        if (enable) {
            aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    RoutePoint routePoint = new RoutePoint();
                    routePoint.setLongitude(DoubleUtils.doubleFormat(latLng.longitude, 7));
                    routePoint.setLatitude(DoubleUtils.doubleFormat(latLng.latitude, 7));
                    routePoint.setDirection("");
                    routePoint.setAltitude(line.getAltitude());
                    routePoint.setAngle(0);
                    routePoint.setPitchAngle(0);
                    routePoint.setMotion("");
                    routePoint.setId(points.size());
                    points.add(routePoint);
                    drawMarkerAndPolyline(latLng);
                    calculateJourneyAndTime();
                    setMarkerChecked(points.size() - 1);
                    hasEdit = true;
                }
            });
        } else {
            aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                }
            });
        }
    }

    private void calculateJourneyAndTime() {
        float journey = 0f;
        if (markerList.size() > 1) {
            for (int i = 1; i < markerList.size(); i++) {
                journey = journey + AMapUtils.calculateLineDistance(markerList.get(i - 1).getPosition(), markerList.get(i).getPosition());
            }
            mTvJourney.setText(DoubleUtils.doubleFormat(journey, 0) + "m");
            float speed = (float) line.getSpeed();
            float second = journey / speed;//秒
            totalTimeSecond = (int) second;
            int hour = (int) DoubleUtils.doubleFormat(second / 3600, 0);
            int minute = (int) DoubleUtils.doubleFormat(second % 3600 / 60, 0);
            int secondRemain = (int) DoubleUtils.doubleFormat(second % 3600 % 60, 0);
            StringBuilder stringBuilder = new StringBuilder();
            if (hour >= 1) {
                stringBuilder.append(hour + "h");
            }
            if (minute >= 1) {
                stringBuilder.append(minute + "m");
            }
            stringBuilder.append(secondRemain + "s");
            mTvTime.setText(stringBuilder.toString());
//            getTimeInterval();//每次计算的时候修改照片数量
        }
    }

    private void initData() {
        dao = MyApplication.dao;
        markerList = new ArrayList<>();
        polylineList = new ArrayList<>();
        Intent intent = getIntent();
        line = intent.getParcelableExtra("line");
        fileNames = (List<String>) intent.getSerializableExtra("names");
        name = intent.getStringExtra("name");
        start_flag = intent.getIntExtra("start_flag", -1);

        mEtFileName.setText(name);
        mEtFileName.setEnabled(false);//设置成false避免关屏开屏之后弹出输入界面
        if (line != null) {
            getPoints(line.getFileName());
            savedFileName = "";
        } else {
            line = new RouteLine();
            line.setSpeed(5.0f);
            line.setAltitude(50);
            line.setHeadingMode("Auto");
            line.setGimbalPitchMode("UsePointSetting");
            line.setActionOnFinish("GoFirstPoint");
            line.setFileName(name);
            savedFileName = line.getFileName();
        }
        oldImageFilePath = line.getImagePath();
        fragmentRouteSetting.getLineDataSuccess(line);
        fragmentPointSetting.setFragmentData(points, line.getAltitude());
        if (points.size() > 0) {
            LatLng latLng = new LatLng(points.get(0).getLatitude(), points.get(0).getLongitude());
            cameraMoveTo(latLng);
        }

        //payload
        final TextView text_payload_ch4 = findViewById(R.id.manualflight_text_payload_ch4);
        final TextView text_payload_err = findViewById(R.id.manualflight_text_payload_err);
        Aircraft aircraft = (Aircraft) MyApplication.getProductInstance();
        if (aircraft != null) {
            final Payload payload = aircraft.getPayload();
            /**
             * payload消息处理
             */
            if (payload != null) {
                payload.setMessageCallback(new Payload.HintMessageCallback() {
                    @Override
                    public void onGetMessage(String s) {
//                        s = "ch4:150 ppm\r\ntmp:%02d C\r\ntmp1:%02d C\r\ntmp2:%02d C\r\nerr:12\r\n";
                        myCh4 = mPref.getInt("alarm_limit", -1);
                        if (myCh4 < 0) {
                            return;
                        }
                        Log.e("payloadInfo", s);
                        String msg = s.replace("\n", "")
                                .replace("\r", "");
                        if (msg.contains("ch4:")
                                && msg.contains("ppm")
                                && msg.contains("err:")) {
                            //甲烷
                            String ch4 = msg.substring(msg.indexOf("ch4:"), msg.indexOf("ppm") + 3);
                            int c = TypeUtils.toInt(ch4.substring(ch4.indexOf("ch4:") + 4, ch4.indexOf("ppm")));
//                            int c = 200;
                            if (c > myCh4) {
                                OnUIUtils.setTextViewColor(text_payload_ch4,
                                        getResources().getColor(R.color.red));
                                AlarmUtils.playAlarmVideo(RouteSettingActivity.this);
                                if (!screenShooted)
                                    screenShooted = ScreenShootUtils.screenShoot(RouteSettingActivity.this);
                            } else {
                                OnUIUtils.setTextViewColor(text_payload_ch4,
                                        getResources().getColor(R.color.forestgreen));
                                AlarmUtils.stopAlarm();
                                screenShooted = false;
                            }
                            OnUIUtils.setTextView(text_payload_ch4, ch4);

                            //错误码
                            Log.e("payloadMsg", "msg=" + msg);
                            Log.e("payloadMsg", "err=" + msg.substring(msg.indexOf("err:") + 4, msg.length()));
                            int e = TypeUtils.toInt(msg.substring(msg.indexOf("err:") + 4, msg.length()));
                            if (e == 0) {
                                OnUIUtils.setTextViewColor(text_payload_err, getResources().getColor(R.color.forestgreen));
                            } else {
                                OnUIUtils.setTextViewColor(text_payload_err, getResources().getColor(R.color.red));
                                if (System.currentTimeMillis() - errTime > 2000){
                                    OnUIUtils.setToast(PayloadErr.getNameByIndex(e));
                                    errTime = System.currentTimeMillis();
                                }
                            }
                            OnUIUtils.setTextView(text_payload_err, PayloadErr.getNameByIndex(e));
                        } else
                            OnUIUtils.setTextView(text_payload_ch4, msg);

//                        if (payloadCb != null)
//                            payloadCb.setData(msg);
                    }
                });
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    }

    private void initView() {
        mRlClear = findViewById(R.id.ll_clear);
        mRlSave = findViewById(R.id.rl_save_btn);
        mRlEdit = findViewById(R.id.rl_edit_btn);
        mEtFileName = findViewById(R.id.et_file_name);
        mLlButtonBar = findViewById(R.id.ll_map_button_bar);
        mLlButtonBar2 = findViewById(R.id.ll_map_button_bar2);
        mIvInfoToggle = findViewById(R.id.iv_hide_menu);
        mRlInfoBtn = findViewById(R.id.rl_route_info_menu_btn);
        mLlInfo = findViewById(R.id.fl_route_info_menu);
        mRlLocation = findViewById(R.id.rl_location);
        mRlDeleteLast = findViewById(R.id.rl_delete_last);
        mRlExchange = findViewById(R.id.rl_exchange);
        mRlCurrentLocation = findViewById(R.id.rl_self_location);
        mRlCompass = findViewById(R.id.rl_compass);
        mIvCompass = findViewById(R.id.iv_compass);
        mRlMapType = findViewById(R.id.rl_map_type);
        mVpMenu = findViewById(R.id.vp_setting);
        mRg = findViewById(R.id.rg_route_setting);
        mRbPoint = findViewById(R.id.rb_point);
        mRbRoute = findViewById(R.id.rb_route);
        mIbFileName = findViewById(R.id.ib_file_name_editable);
        mLlActionMenu = findViewById(R.id.ll_pointsetting_add_action);
        mBtnStart = findViewById(R.id.btn_start);
        mBtnStart.setEnabled(false);
        mTvJourney = findViewById(R.id.tv_route_journey);
        mTvTime = findViewById(R.id.tv_total_time);
        mTvWaypointQty = findViewById(R.id.tv_waypoint_qty);
        mRlRouteSetting = findViewById(R.id.rl_route_setting);
        mRlCotainer = findViewById(R.id.rl_container);

        mIvAdd = findViewById(R.id.iv_add_point_action);
        mIvAdd.setOnClickListener(this);
        mSRev = findViewById(R.id.rev_point_actions);
        mRbPoint.setEnabled(false);
        mRbPoint.setTextColor(getResources().getColor(R.color.gray));
        findViewById(R.id.iv_back_to_point_info).setOnClickListener(this);

        fragmentRouteSetting = new FragmentLineSetting();
        fragmentPointSetting = new FragmentPointSetting();

        viewList.add(fragmentRouteSetting);
        viewList.add(fragmentPointSetting);
        FragmentManager fm = getSupportFragmentManager();
        viewPagerAdapter = new ViewPagerAdapter(fm, viewList);
        mVpMenu.setAdapter(viewPagerAdapter);
        mVpMenu.setCurrentItem(0);

        handler = new Handler(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mSRev.setLayoutManager(linearLayoutManager);
        findViewById(R.id.v_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initListener() {
        mIbFileName.setOnClickListener(this);
        mRlClear.setOnClickListener(this);
        findViewById(R.id.iv_save).setOnClickListener(this);
        findViewById(R.id.iv_edit).setOnClickListener(this);
        mBtnPause = findViewById(R.id.btn_pause);
        mBtnPause.setOnClickListener(this);
        mRlInfoBtn.setOnClickListener(this);
        mRlLocation.setOnClickListener(this);
        mRlDeleteLast.setOnClickListener(this);
        mRlExchange.setOnClickListener(this);
        mRlCurrentLocation.setOnClickListener(this);
        mRlCompass.setOnClickListener(this);
        mRlMapType.setOnClickListener(this);
        mBtnStart.setOnClickListener(this);
        mRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_route:
                        mVpMenu.setCurrentItem(0);
                        mRbPoint.setChecked(false);
                        break;
                    case R.id.rb_point:
                        mVpMenu.setCurrentItem(1);
                        mRbRoute.setChecked(false);
                        break;
                }
            }
        });

        mVpMenu.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    mRbRoute.setChecked(true);
                } else {
                    mRbPoint.setChecked(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                int position = markerList.indexOf(marker);
                setMarkerChecked(position);
                return true;
            }
        });
    }

    private void showActionPopupWindow() {
        View convertView = LayoutInflater.from(this).inflate(R.layout.popup_action_type, null);
        convertView.findViewById(R.id.tv_select_action_hover).setOnClickListener(this);
        convertView.findViewById(R.id.tv_select_action_shoot_photo).setOnClickListener(this);
        convertView.findViewById(R.id.tv_select_action_StartRecording).setOnClickListener(this);
        convertView.findViewById(R.id.tv_select_action_StopRecording).setOnClickListener(this);
        convertView.findViewById(R.id.tv_select_action_AircraftYaw).setOnClickListener(this);
        convertView.findViewById(R.id.tv_select_action_GimbalPitch).setOnClickListener(this);

        if (actionPopWindow == null) {
            actionPopWindow = new PopupWindow(convertView, RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT, true);
        }
        actionPopWindow.setTouchable(true);
        actionPopWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });
        actionPopWindow.showAsDropDown(mIvAdd, -200, 20);

    }

    public void setMarkerChecked(int position) {
        for (int i = 0; i < markerList.size(); i++) {
            String content = i == 0 ? "S" : i + 1 + "";
            if (position == i) {
                markerList.get(i).setIcon(BitmapDescriptorFactory.fromBitmap(getMyBitmap(R.drawable.ic_waypoint_selected, content, R.color.white)));
                mRbPoint.setEnabled(true);
                mRbPoint.setTextColor(getResources().getColor(R.color.white));
            } else {
                markerList.get(i).setIcon(BitmapDescriptorFactory.fromBitmap(getMyBitmap(R.drawable.ic_waypoint_normal, content, R.color.dodgerblue)));
            }
        }
        selectMarkerPosition = position;
        fragmentPointSetting.onPointSelected(position);
        mLlActionMenu.setVisibility(View.GONE);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        try {
            super.onWindowFocusChanged(hasFocus);
            if (setComplete) {
                return;
            }
            if (start_flag == CREATE) {
                mRlEdit.setVisibility(View.GONE);
                mRlSave.setVisibility(View.VISIBLE);
                mIvInfoToggle.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.arrow_right));
                isRouteMenuVisible = true;
                setMapClickListEnable(true);
                mBtnStart.setEnabled(false);
            } else {
                mRlEdit.setVisibility(View.VISIBLE);
                mRlSave.setVisibility(View.GONE);
                mIvInfoToggle.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.arrow_left));
                addAnimationHide(mLlInfo, 50);
                addAnimationHide(mRlInfoBtn, 50);
                addAnimationHide(mLlButtonBar, 50);
                mRlInfoBtn.setVisibility(View.INVISIBLE);
                mLlButtonBar2.setVisibility(View.GONE);
                isRouteMenuVisible = false;
                setMapClickListEnable(false);
                if (product.isConnected()){
                    mBtnStart.setEnabled(true);
                }
            }
            CameraUpdate mCameraUpdate = CameraUpdateFactory.zoomTo(17);//放缩等级17
            aMap.animateCamera(mCameraUpdate);
            setComplete = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addAnimationHide(View view, int duration) {
        float currentX = mLlInfo.getTranslationX();
        float menuX = mLlInfo.getWidth();
        ObjectAnimator animatorHide = ObjectAnimator.ofFloat(view, "translationX", currentX, menuX);
        animatorHide.setDuration(duration);
        animatorHide.start();
        isRouteMenuVisible = false;
    }

    private void addAnimationShow(View view, int duration) {
        float menuX = mLlInfo.getWidth();
        ObjectAnimator animatorHide = ObjectAnimator.ofFloat(view, "translationX", menuX, 0);
        animatorHide.setDuration(duration);
        animatorHide.start();
        isRouteMenuVisible = true;
    }


    private boolean isFileNameRepeat(String fileName) {
        if (fileNames == null) {
            return false;
        }
        for (int i = 0; i < fileNames.size(); i++) {
            if (fileName.equals(fileNames.get(i))) {
                return true;
            }
        }
        return false;
    }

    private void getPoints(String fileName) {
        points.clear();
        points.addAll(dao.queryPoints(fileName));
        aMap.clear();
        markerList.clear();
        polylineList.clear();
        for (int i = 0; i < points.size(); i++) {
            LatLng latLng = new LatLng(points.get(i).getLatitude(), points.get(i).getLongitude());
            drawMarkerAndPolyline(latLng);
        }
        calculateJourneyAndTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        removeListener();
    }

    private void drawMarkerAndPolyline(LatLng latLng) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        String word;
        if (markerList.size() == 0) {
            word = "S";
        } else {
            word = markerList.size() + 1 + "";
        }
        final BitmapDescriptor bd = BitmapDescriptorFactory.fromBitmap(getMyBitmap(R.drawable.ic_waypoint_normal, word, R.color.dodgerblue));
        markerOptions.icon(bd);
        markerOptions.anchor(0.5f, 0.5f);
        Marker marker = aMap.addMarker(markerOptions);
        if (markerList.size() > 0) {
            float angle = getMarkeraAngle(markerList.get(markerList.size() - 1).getPosition(), marker.getPosition());
            markerList.get(markerList.size() - 1).setRotateAngle(angle);
            marker.setRotateAngle(angle);
        }
        marker.setDraggable(true);
        markerList.add(marker);
        int length = markerList.size();
        if (length > 1) {//不包括定位点
            polylineList.add(aMap.addPolyline(new PolylineOptions().add(markerList.get(length - 2).getPosition(), markerList.get(length - 1).getPosition())));
        }
        mTvWaypointQty.setText(markerList.size() + "");
    }

    private float getMarkeraAngle(LatLng preLatLng, LatLng newLatlng) {
        double y = Math.sin(newLatlng.longitude - preLatLng.longitude) * Math.cos(newLatlng.latitude);
        double x = Math.cos(preLatLng.latitude) * Math.sin(newLatlng.latitude) - Math.sin(preLatLng.latitude) * Math.cos(newLatlng.latitude) * Math.cos(newLatlng.longitude - preLatLng.longitude);
        double brng = Math.atan2(y, x);
        brng = Math.toDegrees(brng);
        if (brng < 0)
            brng = brng + 360;
        return (float) brng;
    }

    //在图片上加字
    protected Bitmap getMyBitmap(int id, String pm_val, int color) {
        Bitmap bitmap = scaleBitmap(BitmapDescriptorFactory.fromResource(id).getBitmap(), 0.7f);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight());
        Canvas canvas = new Canvas(bitmap);
        TextPaint textPaint = new TextPaint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(32f);
        textPaint.setColor(getResources().getColor(color));
        if (!"S".equals(pm_val)) {
            int count = Integer.parseInt(pm_val);
            if (count >= 10 && count < 100) {
                canvas.drawText(pm_val, 23, 53, textPaint);// 设置bitmap上面的文字位置
            } else if (count < 10) {
                canvas.drawText(pm_val, 32, 53, textPaint);// 设置bitmap上面的文字位置
            }
        } else {
            canvas.drawText(pm_val, 32, 53, textPaint);// 设置bitmap上面的文字位置
        }
        return bitmap;
    }

    /**
     * 按比例缩放图片
     *
     * @param origin 原图
     * @param ratio  比例
     * @return 新的bitmap
     */
    private Bitmap scaleBitmap(Bitmap origin, float ratio) {
        if (origin == null) {
            return null;
        }
        int width = origin.getWidth();
        int height = origin.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(ratio, ratio);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (newBM.equals(origin)) {
            return newBM;
        }
        origin.recycle();
        return newBM;
    }

    private void clearMarkers() {
        for (int i = 0; i < markerList.size(); i++) {
            markerList.get(i).destroy();
        }
        markerList.clear();
    }

    private void clearPolylines() {
        for (int i = 0; i < polylineList.size(); i++) {
            polylineList.get(i).remove();
        }
        polylineList.clear();
    }


    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_clear:
                for (int i = 0; i < markerList.size(); i++) {
                    markerList.get(i).destroy();
                }
                for (int i = 0; i < polylineList.size(); i++) {
                    polylineList.get(i).remove();
                }
                polylineList.clear();
                markerList.clear();
                points.clear();
                waypointList.clear();
                if (waypointMissionBuilder != null) {
                    waypointMissionBuilder.waypointList(waypointList);
                }
                setMarkerChecked(0);
                updateDroneLocation();
                mTvWaypointQty.setText("0");
                break;
            case R.id.iv_save:
                saveRoute();
                break;
            case R.id.iv_edit:
                hasEdit = true;
                mRlEdit.setVisibility(View.GONE);
                mRlSave.setVisibility(View.VISIBLE);
                mLlButtonBar2.setVisibility(View.VISIBLE);
                mRlInfoBtn.setVisibility(View.VISIBLE);
                setMapClickListEnable(true);
                addAnimationShow(mLlInfo, 500);
                addAnimationShow(mRlInfoBtn, 500);
                addAnimationShow(mLlButtonBar, 500);
                mIvInfoToggle.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.arrow_right));
                break;
            case R.id.rl_route_info_menu_btn:
                if (isRouteMenuVisible) {
                    addAnimationHide(mLlInfo, 500);
                    addAnimationHide(mRlInfoBtn, 500);
                    addAnimationHide(mLlButtonBar, 500);
                    mIvInfoToggle.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.arrow_left));
                    isRouteMenuVisible = false;
                } else {
                    addAnimationShow(mLlInfo, 500);
                    addAnimationShow(mRlInfoBtn, 500);
                    addAnimationShow(mLlButtonBar, 500);
                    mIvInfoToggle.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.arrow_right));
                    isRouteMenuVisible = true;
                }
                break;
            case R.id.rl_location:
                if (mLocationMarker == null) {
                    LatLng latLng = getMapCenterPoint();
                    mLocationMarker = aMap.addMarker(new MarkerOptions().position(latLng));

                } else {
                    mLocationMarker.destroy();
                    mLocationMarker = null;
                }
                break;
            case R.id.rl_delete_last:
                int index = markerList.size() - 1;
                if (index >= 0) {
                    markerList.get(index).destroy();
                    markerList.remove(index);
                }
                int lineIndex = polylineList.size() - 1;
                if (lineIndex >= 0) {
                    polylineList.get(lineIndex).remove();
                    polylineList.remove(lineIndex);
                }
                int pointIndex = points.size() - 1;
                if (pointIndex >= 0) {
                    points.remove(pointIndex);

                }
                if (pointIndex == selectMarkerPosition) {
                    setMarkerChecked(pointIndex - 1);
                }
                mTvWaypointQty.setText(markerList.size() + "");
                break;
            case R.id.rl_exchange:
                clearMarkers();
                clearPolylines();
                Collections.reverse(points);
                for (int i = 0; i < points.size(); i++) {
                    LatLng latLng = new LatLng(points.get(i).getLatitude(), points.get(i).getLongitude());
                    drawMarkerAndPolyline(latLng);
                }
                calculateJourneyAndTime();
                break;
            case R.id.rl_self_location:
                Location location = aMap.getMyLocation();
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                cameraMoveTo(latLng);
                break;
            case R.id.rl_compass:
                if (compass != null) {
                    compass.startCalibration(new CommonCallbacks.CompletionCallback() {
                        @Override
                        public void onResult(DJIError djiError) {
                            if (djiError == null) {
                                mIvCompass.setEnabled(true);
                            } else {
                                mIvCompass.setEnabled(false);
                            }
                        }
                    });
                }
                break;
            case R.id.rl_map_type:
                showPopupWindow();
                break;
            case R.id.ll_standard_map:
                aMap.setMapType(com.amap.api.maps2d.AMap.MAP_TYPE_NORMAL);
                break;
            case R.id.ll_satellite_map:
                aMap.setMapType(com.amap.api.maps2d.AMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.ib_file_name_editable:
                mEtFileName.setEnabled(true);
                break;
            case R.id.iv_add_point_action:
                showActionPopupWindow();
                break;
            case R.id.tv_select_action_hover:
                actions.add(new PointAction("Hovering", "10000"));
                actionAdapter.notifyDataSetChanged();
                actionPopWindow.dismiss();
                break;
            case R.id.tv_select_action_shoot_photo:
                actions.add(new PointAction("ShootPhoto", ""));
                actionAdapter.notifyDataSetChanged();
                actionPopWindow.dismiss();
                break;
            case R.id.tv_select_action_StartRecording:
                actions.add(new PointAction("StartRecording", ""));
                actionAdapter.notifyDataSetChanged();
                actionPopWindow.dismiss();
                break;
            case R.id.tv_select_action_StopRecording:
                actions.add(new PointAction("StopRecording", ""));
                actionAdapter.notifyDataSetChanged();
                actionPopWindow.dismiss();
                break;
            case R.id.tv_select_action_AircraftYaw:
                actions.add(new PointAction("AircraftYaw", "0"));
                actionAdapter.notifyDataSetChanged();
                actionPopWindow.dismiss();
                break;
            case R.id.tv_select_action_GimbalPitch:
                actions.add(new PointAction("GimbalPitch", "0"));
                actionAdapter.notifyDataSetChanged();
                actionPopWindow.dismiss();
                break;
            case R.id.iv_back_to_point_info:
//                mLlActionMenu.setVisibility(View.GONE);
                hideActionsSelectMenu();
                break;
            case R.id.btn_start:
                if (hasEdit) {
                    showToast("请先保存任务");
                    return;
                }
                mRlRouteSetting.setVisibility(View.GONE);
                mRlCotainer.setVisibility(View.VISIBLE);
                if (fragmentFlyPrepare == null) {
                    fragmentFlyPrepare = new FragmentFlyPrepare();
                    fragmentManager = getSupportFragmentManager();
                    fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.add(R.id.rl_container, fragmentFlyPrepare).commit();
                }
                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.show(fragmentFlyPrepare).commit();
                cameraUpdate();
//                setWayPoints();
                break;
            case R.id.btn_pause:
                pauseWayPointMission();
                break;
        }
    }

    public void hidePrepareFragment() {
        mRlRouteSetting.setVisibility(View.VISIBLE);
        mRlCotainer.setVisibility(View.GONE);
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.hide(fragmentFlyPrepare).commit();
    }

    public void setWayPoints() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hidePrepareFragment();
            }
        });

        mFinishedAction = WaypointMissionFinishedAction.GO_HOME;
        switch (line.getActionOnFinish()) {
            case "Hover":
                mFinishedAction = WaypointMissionFinishedAction.NO_ACTION;
                break;
            case "GoHome":
                mFinishedAction = WaypointMissionFinishedAction.GO_HOME;
                break;
            case "AutoLand":
                mFinishedAction = WaypointMissionFinishedAction.AUTO_LAND;
                break;
            case "GoFirstPoint":
                mFinishedAction = WaypointMissionFinishedAction.GO_FIRST_WAYPOINT;
                break;
        }
        mHeadingMode = WaypointMissionHeadingMode.AUTO;
        switch (line.getHeadingMode()) {
            case "Auto":
                mHeadingMode = WaypointMissionHeadingMode.AUTO;
                break;
            case "ControlledByRC":
                mHeadingMode = WaypointMissionHeadingMode.CONTROL_BY_REMOTE_CONTROLLER;
                break;
            case "UsePointSetting":
                mHeadingMode = WaypointMissionHeadingMode.USING_WAYPOINT_HEADING;
                break;
        }
        for (int i = 0; i < points.size(); i++) {
            RoutePoint point = points.get(i);
            Waypoint waypoint = new Waypoint(point.getLatitude(), point.getLongitude(), (float) point.getAltitude());
            if (waypointMissionBuilder != null) {
                waypointList.add(waypoint);
                waypointMissionBuilder.waypointList(waypointList).waypointCount(waypointList.size());
            } else {
                waypointMissionBuilder = new WaypointMission.Builder();
                waypointList.add(waypoint);
                waypointMissionBuilder.waypointList(waypointList).waypointCount(waypointList.size());
            }
        }
        waypointMissionBuilder.finishedAction(mFinishedAction)
                .headingMode(mHeadingMode)
                .autoFlightSpeed((float) line.getSpeed())
                .maxFlightSpeed((float) line.getSpeed())
                .flightPathMode(WaypointMissionFlightPathMode.NORMAL)
                .setExitMissionOnRCSignalLostEnabled(line.getStopWhenLost() == 1 ? true : false);
        if (waypointMissionBuilder.getWaypointList().size() > 0) {
            for (int i = 0; i < waypointMissionBuilder.getWaypointList().size(); i++) {
                waypointMissionBuilder.getWaypointList().get(i).altitude = (float) line.getAltitude();
            }
            OnUIUtils.setToast("Set Waypoint attitude successfully");
        }else{
            OnUIUtils.setToast("WaypointList().size() = 0");
        }
        DJIError error = getWaypointMissionOperator().loadMission(waypointMissionBuilder.build());
        if (error == null) {
            OnUIUtils.setToast("loadWaypoint succeeded");
            uploadWayPointMission();
        } else {
            OnUIUtils.setToast("loadWaypoint failed " + error.getDescription());
        }
    }

    private void uploadWayPointMission() {
        getWaypointMissionOperator().uploadMission(new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError error) {
                if (error == null) {
                    OnUIUtils.setToast("Mission upload successfully!");
                    startWaypointMission();
                } else {
                    OnUIUtils.setToast("Mission upload failed, error: " + error.getDescription() + " retrying...");
                    getWaypointMissionOperator().retryUploadMission(null);
                }
            }
        });

    }

    private void startWaypointMission() {
        getWaypointMissionOperator().startMission(new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError error) {
                if (error == null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mBtnStart.setVisibility(View.GONE);
                            mBtnPause.setVisibility(View.VISIBLE);
                        }
                    });
                }
                showToast("Mission Start: " + (error == null ? "Successfully" : error.getDescription()));
            }
        });
    }

    private void stopWaypointMission() {

        getWaypointMissionOperator().stopMission(new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError error) {
                if (error == null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mBtnStart.setVisibility(View.VISIBLE);
                            mBtnPause.setVisibility(View.GONE);
                        }
                    });
                }
                showToast("Mission Stop: " + (error == null ? "Successfully" : error.getDescription()));
            }
        });

    }

    private void pauseWayPointMission(){
        getWaypointMissionOperator().pauseMission(new CommonCallbacks.CompletionCallback() {
            @Override
            public void onResult(DJIError djiError) {
                if (djiError == null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mBtnStart.setVisibility(View.VISIBLE);
                            mBtnPause.setVisibility(View.GONE);
                        }
                    });
                }
            }
        });
    }

    private void cameraMoveTo(LatLng latLng) {
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
    }

    private void addListener() {
        if (getWaypointMissionOperator() != null) {
            getWaypointMissionOperator().addListener(eventNotificationListener);
        }
    }

    private void removeListener() {
        if (getWaypointMissionOperator() != null) {
            getWaypointMissionOperator().removeListener(eventNotificationListener);
        }
        if (mFlightController!=null){
            mFlightController.setStateCallback(null);
        }
    }

    public WaypointMissionOperator getWaypointMissionOperator() {
        if (instance == null) {
            if (DJISDKManager.getInstance() == null) {
                return null;
            }
            if (DJISDKManager.getInstance().getMissionControl() == null) {
                return null;
            }
            instance = DJISDKManager.getInstance().getMissionControl().getWaypointMissionOperator();
        }
        return instance;
    }

    private WaypointMissionOperatorListener eventNotificationListener = new WaypointMissionOperatorListener() {
        @Override
        public void onDownloadUpdate(WaypointMissionDownloadEvent downloadEvent) {

        }

        @Override
        public void onUploadUpdate(WaypointMissionUploadEvent uploadEvent) {

        }

        @Override
        public void onExecutionUpdate(WaypointMissionExecutionEvent executionEvent) {

        }

        @Override
        public void onExecutionStart() {

        }

        @Override
        public void onExecutionFinish(@Nullable final DJIError error) {
            showToast("Execution finished: " + (error == null ? "Success!" : error.getDescription()));
        }
    };

    private void saveRoute() {
        if (markerList.size() == 0) {
            showToast("没有航线，请重试");
            return;
        }
        if ("".equals(savedFileName)) {
            savedFileName = mEtFileName.getText().toString().trim();
        }
        String fileName = mEtFileName.getText().toString().trim();
        if ("".equals(fileName)) {
            showToast("文件名不能为空");
            return;
        }
        if (isFileNameRepeat(fileName)) {
            showToast("文件名已存在");
            return;
        }
        //截图之前将地图移动到marker位置
        CameraUpdate mCameraUpdate = CameraUpdateFactory.zoomTo(17);//放缩等级17
        aMap.animateCamera(mCameraUpdate);
        cameraMoveTo(markerList.get(0).getPosition());
        aMap.getMapScreenShot(this);
    }

    /**
     * by moos on 2017/09/05
     * func:获取屏幕中心的经纬度坐标
     *
     * @return
     */
    public LatLng getMapCenterPoint() {
        int left = mapView.getLeft();
        int top = mapView.getTop();
        int right = mapView.getRight();
        int bottom = mapView.getBottom();
        // 获得屏幕点击的位置
        int x = (int) (mapView.getX() + (right - left) / 2);
        int y = (int) (mapView.getY() + (bottom - top) / 2);
        Projection projection = aMap.getProjection();
        LatLng pt = projection.fromScreenLocation(new Point(x, y));

        return pt;
    }

    private void showPopupWindow() {
        View convertView = LayoutInflater.from(this).inflate(R.layout.popup_map_type, null);
        LinearLayout llStandard = convertView.findViewById(R.id.ll_standard_map);
        llStandard.setOnClickListener(this);
        LinearLayout llSatellite = convertView.findViewById(R.id.ll_satellite_map);
        llSatellite.setOnClickListener(this);
        if (mPopupWindow == null) {
            mPopupWindow = new PopupWindow(convertView, RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT, true);
        }
        mPopupWindow.setTouchable(true);
        mPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return false;
            }
        });

        mPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup_grey_bg));
        mPopupWindow.showAsDropDown(mRlMapType, -200, 20);
    }

    public RouteLine getRouteLine() {
        return line;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (hasEdit) {
            new CommomDialog(this, R.style.commondialog, "当前任务未保存，是否先保存再退出？", new CommomDialog.OnCloseListener() {
                @Override
                public void onClick(CommomDialog dialog, boolean confirm) {
                    if (confirm) {
                        saveRoute();
                    }
                    dialog.dismiss();
                    RouteSettingActivity.this.finish();
                }
            }).setTitle("提示").show();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void upDatePointAndLine(int position) {
        if (markerList.size() == 0) {
            return;
        }
        if (position == (markerList.size() - 1)) {
            polylineList.get(position - 1).remove();
            polylineList.set(position - 1, aMap.addPolyline(new PolylineOptions().add(markerList.get(position - 1).getPosition(), markerList.get(position).getPosition())));
        } else if (position == 0) {
            polylineList.get(position).remove();
            polylineList.set(position, aMap.addPolyline(new PolylineOptions().add(markerList.get(position).getPosition(), markerList.get(position + 1).getPosition())));
        } else {
            polylineList.get(position).remove();
            polylineList.get(position - 1).remove();
            polylineList.set(position, aMap.addPolyline(new PolylineOptions().add(markerList.get(position).getPosition(), markerList.get(position + 1).getPosition())));
            polylineList.set(position - 1, aMap.addPolyline(new PolylineOptions().add(markerList.get(position - 1).getPosition(), markerList.get(position).getPosition())));
        }
    }

    @Override
    public boolean handleMessage(Message message) {
        return false;
    }

    public void showActionsSelectMenu() {
        mLlActionMenu.setVisibility(View.VISIBLE);
    }

    public void hideActionsSelectMenu() {
        mLlActionMenu.setVisibility(View.GONE);
    }

    public void upDateActionInfo(List<PointAction> actions) {
        this.actions = actions;
        actionAdapter = new ActionAdapter(actions, handler);
        mSRev.setAdapter(actionAdapter);
    }

    //截图成功
    @Override
    public void onMapScreenShot(Bitmap bitmap) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = sdf.format(new Date());
        String filePath = Environment.getExternalStorageDirectory() + "/UAV/MapShot";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        String imagePath = filePath + "/" + dateStr + ".png";
        if (null == bitmap) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(
                    imagePath);
            boolean b = bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            try {
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (b)
                showToast("截屏成功");
            else {
                showToast("截屏失败");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //保存
        String fileName = mEtFileName.getText().toString().trim();
        String place = myLocationStr;
        line.setUpdateTime(System.currentTimeMillis());
        line.setUpdatePlace(place);
        line.setFileName(fileName);
        line.setType("Waypoint");
        line.setImagePath(imagePath);
        if (start_flag == CREATE) {
            dao.addRoute(line);
            for (int i = 0; i < points.size(); i++) {
                dao.addPoint(i, points.get(i), fileName);
                dao.addPointActions(fileName, points.get(i));
            }
        }
        if (start_flag == UPDATE) {
            dao.updateRoute(line, savedFileName);
            dao.updatePoints(fileName, points);
            dao.updatePointActions(fileName, points);
            ImageFileUtils.deleteImageFile(oldImageFilePath);
        }
        mRlEdit.setVisibility(View.VISIBLE);
        mRlSave.setVisibility(View.GONE);
        showToast("保存成功!");
        //
        if (product.isConnected()) {
            mBtnStart.setEnabled(true);
        }
        start_flag = UPDATE;//保存成功之后将启动类型改为更新，此时再做修改视为更新航线
        savedFileName = fileName;
        oldImageFilePath = line.getImagePath();//保存更新之前的图片文件路径
        mRlEdit.setVisibility(View.VISIBLE);
        mRlSave.setVisibility(View.GONE);
        addAnimationHide(mLlInfo, 50);
        addAnimationHide(mRlInfoBtn, 50);
        addAnimationHide(mLlButtonBar, 50);
        mRlInfoBtn.setVisibility(View.INVISIBLE);
        mLlButtonBar2.setVisibility(View.GONE);
        isRouteMenuVisible = true;
        hasEdit = false;
        setMapClickListEnable(false);
    }

    @Override
    public void onMapScreenShot(Bitmap bitmap, int i) {

    }


}
